﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using Common;

namespace SERS.ExamRoom
{
    /// <summary>
    /// Service 的摘要说明
    /// </summary>
    public class Service : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            HttpRequest Request = context.Request;
            HttpResponse Response = context.Response;
            string str = "";
            switch (Request["action"])
            {
                case "GetNewExam"://生成或获取题库
                    str = GetNewExam(context);
                    break;
                case "DelNewExam"://清空题库
                    str = DelNewExam(context);
                    break;
                case "GetAllExam"://获取所有模拟题库
                    str = GetAllExam(context);
                    break;
                case "Answer"://答题
                    str = Answer(context);
                    break;
                case "Search"://查询题目
                    str = Search(context);
                    break;
            }
            Response.Write(str);
        }

        /// <summary>
        /// 搜索题
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string Search(HttpContext context)
        {
            HttpRequest Request = context.Request;
            HttpResponse Response = context.Response;
            ExamRoomList exams = new ExamRoomList();
            string str = "";
            int id = 1;
            string title = "";
            if (!string.IsNullOrEmpty(Request["id"]))
            {
                id = Convert.ToInt32(Request["id"]);
            }
            if (!string.IsNullOrEmpty(Request["title"]))
            {
                title = Request["title"];
                title = System.Web.HttpUtility.UrlDecode(title);
            }

            string _path = context.Server.MapPath("Exam\\Exam.txt");
            if (id == 2009 || id == 2010 || id == 2011 || id == 2012)
            {
                _path = context.Server.MapPath("Exam\\" + id + ".txt");
                str = ReaderTxt(_path);
                if (!string.IsNullOrEmpty(str))
                {
                    exams = JsonConvert.DeserializeObject<ExamRoomList>(str);
                    var result = exams.list.Where(p => p.question.Contains(title));
                    str = JsonConvert.SerializeObject(result);
                }
            }
            else
            {
                str = ReaderTxt(_path);
                if (!string.IsNullOrEmpty(str))
                {
                    List<ExamRoomList> list = new List<ExamRoomList>();
                    list = JsonConvert.DeserializeObject<List<ExamRoomList>>(str);
                    exams = list.Where(a => a.id == id).FirstOrDefault();
                    var result = exams.list.Where(p => p.question.Contains(title));
                    str = JsonConvert.SerializeObject(result);
                }
            }
            return str;
        }

        /// <summary>
        /// 清除题库
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string Answer(HttpContext context)
        {
            HttpRequest Request = context.Request;
            HttpResponse Response = context.Response;
            List<ExamRoomList> list = new List<ExamRoomList>();
            string str = "";
            int id = 1;
            int cid = 1;
            if (!string.IsNullOrEmpty(Request["id"]))
            {
                id = Convert.ToInt32(Request["id"]);
            }
            if (!string.IsNullOrEmpty(Request["cid"]))
            {
                cid = Convert.ToInt32(Request["cid"]);
            }

            string _path = context.Server.MapPath("Exam\\Exam.txt");
            if (id == 2009 || id == 2010 || id == 2011 || id == 2012)
            {
                _path = context.Server.MapPath("Exam\\" + id + ".txt");
                UpdateExamT(context);
            }
            else
            {
                UpdateExam(context);
            }
            str = ReaderTxt(_path);
            return str;
        }

        /// <summary>
        /// 更新试题
        /// </summary>
        /// <param name="context"></param>
        public void UpdateExamT(HttpContext context)
        {
            HttpRequest Request = context.Request;
            HttpResponse Response = context.Response;
            ExamRoomList exams = new ExamRoomList();
            int id = 1;
            int cid = 1;
            if (!string.IsNullOrEmpty(Request["id"]))
            {
                id = Convert.ToInt32(Request["id"]);
            }
            if (!string.IsNullOrEmpty(Request["cid"]))
            {
                cid = Convert.ToInt32(Request["cid"]);
            }
            string _path = context.Server.MapPath("Exam\\" + id + ".txt");
            string str = ReaderTxt(_path);
            if (!string.IsNullOrEmpty(str))
            {
                exams = JsonConvert.DeserializeObject<ExamRoomList>(str);
            }

            var result = exams.list.Where(a => a.id == cid).FirstOrDefault();
            //exams.list.Remove(result);
            if (!string.IsNullOrEmpty(Request["chooseanswer"]))
            {
                result.chooseanswer = Request["chooseanswer"];
            }

            if (!string.IsNullOrEmpty(Request["notebook"]))
            {
                result.notebook = Request["notebook"];
            }

            if (!string.IsNullOrEmpty(Request["ifcollect"]))
            {
                result.ifcollect = Convert.ToInt32(Request["ifcollect"]);
            }

            if (!string.IsNullOrEmpty(Request["errorbook"]))
            {
                result.errorbook = Request["errorbook"];
            }
            if (!string.IsNullOrEmpty(Request["ifsubmit"]))
            {
                exams.ifsubmit = Convert.ToInt32(Request["ifsubmit"]);
            }
            exams.list = exams.list.OrderBy(a => a.id).ToList();
            //exams.list.Add(result);
            str = JsonConvert.SerializeObject(exams);
            WriteTxt(_path, str);
        }

        /// <summary>
        /// 更新模拟试题
        /// </summary>
        /// <param name="context"></param>
        public void UpdateExam(HttpContext context)
        {
            HttpRequest Request = context.Request;
            HttpResponse Response = context.Response;
            List<ExamRoomList> list = new List<ExamRoomList>();
            int id = 1;
            int cid = 1;
            if (!string.IsNullOrEmpty(Request["id"]))
            {
                id = Convert.ToInt32(Request["id"]);
            }
            if (!string.IsNullOrEmpty(Request["cid"]))
            {
                cid = Convert.ToInt32(Request["cid"]);
            }
            string _path = context.Server.MapPath("Exam\\Exam.txt");
            string str = ReaderTxt(_path);
            if (!string.IsNullOrEmpty(str))
            {
                list = JsonConvert.DeserializeObject<List<ExamRoomList>>(str);
            }
            var examList = list.Where(p => p.id == id).FirstOrDefault();
            list.Remove(examList);

            var result = examList.list.Where(a => a.id == cid).FirstOrDefault();

            if (!string.IsNullOrEmpty(Request["chooseanswer"]))
            {
                result.chooseanswer = Request["chooseanswer"];
            }

            if (!string.IsNullOrEmpty(Request["notebook"]))
            {
                result.notebook = Request["notebook"];
            }

            if (!string.IsNullOrEmpty(Request["ifcollect"]))
            {
                result.ifcollect = Convert.ToInt32(Request["ifcollect"]);
            }

            if (!string.IsNullOrEmpty(Request["errorbook"]))
            {
                result.errorbook = Request["errorbook"];
            }
            if (!string.IsNullOrEmpty(Request["ifsubmit"]))
            {
                examList.ifsubmit = Convert.ToInt32(Request["ifsubmit"]);
            }
            list.Add(examList);
            list = list.OrderBy(p => p.id).ToList();
            str = JsonConvert.SerializeObject(list);
            WriteTxt(_path, str);
        }

        /// <summary>
        /// 获取所有模拟题库
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string GetAllExam(HttpContext context)
        {
            string _path = context.Server.MapPath("Exam\\Exam.txt");
            string str = ReaderTxt(_path);
            return str;
        }

        /// <summary>
        /// 清除题库
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string DelNewExam(HttpContext context)
        {
            HttpRequest Request = context.Request;
            HttpResponse Response = context.Response;
            List<ExamRoomList> list = new List<ExamRoomList>();
            string str = "0";
            int id = 1;
            if (!string.IsNullOrEmpty(Request["id"]))
            {
                id = Convert.ToInt32(Request["id"]);
            }
            string _path = context.Server.MapPath("Exam\\Exam.txt");
            str = ReaderTxt(_path);
            if (!string.IsNullOrEmpty(str))
            {
                list = JsonConvert.DeserializeObject<List<ExamRoomList>>(str);
            }
            var result = list.Where(p => p.id == id).FirstOrDefault();
            list.Remove(result);
            str = JsonConvert.SerializeObject(list);
            WriteTxt(_path, str);
            return str;
        }

        object locker = new object();

        /// <summary>
        /// 生成模拟题库
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string CreateNewExam(HttpContext context)
        {
            HttpRequest Request = context.Request;
            HttpResponse Response = context.Response;
            string str = "";
            List<ExamRoomList> list = new List<ExamRoomList>();
            int id = 1;
            if (!string.IsNullOrEmpty(Request["id"]))
            {
                id = Convert.ToInt32(Request["id"]);
            }
            string _path = context.Server.MapPath("Exam\\Exam.txt");
            str = ReaderTxt(_path);
            if (!string.IsNullOrEmpty(str))
            {
                list = JsonConvert.DeserializeObject<List<ExamRoomList>>(str);
            }
            var result = list.Where(p => p.id == id).FirstOrDefault();

            if (result == null)
            {
                ExamRoomList exams = GetExamRoomList();
                exams.id = id;
                exams.ifsubmit = 0;
                exams.exams = 1;
                list.Add(exams);
                list = list.OrderBy(p => p.id).ToList();
                str = JsonConvert.SerializeObject(list);
                WriteTxt(_path, str);
            }
            result = list.Where(p => p.id == id).FirstOrDefault();
            str = JsonConvert.SerializeObject(result);
            return str;
        }

        /// <summary>
        /// 生成试题并获取
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string GetNewExam(HttpContext context)
        {
            HttpRequest Request = context.Request;
            HttpResponse Response = context.Response;
            string str = "";
            string id = Request["id"];
            if (string.IsNullOrEmpty(id))
            {
                id = "1";
            }
            if (id == "2009" || id == "2010" || id == "2011" || id == "2012")
            {
                string _path = context.Server.MapPath("Exam\\" + id + ".txt");
                str = ReaderTxt(_path);
                return str;
            }
            else
            {
                return CreateNewExam(context);
            }
        }

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="_path">路径</param>
        /// <returns></returns>
        public string ReaderTxt(string _path)
        {
            string str = "";
            lock (locker)
            {
                if (File.Exists(_path))
                {
                    using (FileStream fs = File.Open(_path, FileMode.Open))
                    {
                        using (StreamReader reader = new StreamReader(fs, Encoding.UTF8))
                        {
                            str = reader.ReadLine();
                            reader.Close();
                            reader.Dispose();
                        }
                        fs.Close();
                        fs.Dispose();
                    }
                }
            }
            return str;
        }

        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="_path">路径</param>
        /// <param name="str">写入内容</param>
        public void WriteTxt(string _path, string str)
        {
            lock (locker)
            {
                using (StreamWriter sw = new StreamWriter(_path, false, Encoding.UTF8))
                {
                    sw.Write(str);
                    sw.Close();
                    sw.Dispose();
                }
            }
        }

        /// <summary>
        /// 生成题库
        /// </summary>
        /// <returns></returns>
        public ExamRoomList GetExamRoomList()
        {
            ExamRoomList exams = new ExamRoomList();
            exams.ifsubmit = 0;
            List<ExamRoom> list = new List<ExamRoom>();
            for (int i = 0; i < 100; i++)
            {
                ExamRoom model = new ExamRoom();
                model.id = i + 1;
                model.flog = 0;
                model.title = "第1题，单项选择题(单选)(本题1分)";
                model.question = "关于推选性标准，下列说法正确的是" + model.id;
                List<string> answer = new List<string>();
                answer.Add("A. 不管是在什么级别的推荐性标准，都可以不执行");
                answer.Add("B. 如果是推荐性地方标准，也必须执行");
                answer.Add("C. 如果是推荐性行业标准，也必须执行");
                answer.Add("D. 如果是推荐性国家标准，也必须执行");
                model.answer = answer;
                model.answerdetail = "解释";
                model.trueanswer = "2";
                model.ifcollect = 0;
                list.Add(model);
            }
            exams.list = list;
            return exams;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

    public class ExamRoomList
    {
        /// <summary>
        /// 编号
        /// </summary>
        public int id
        {
            get;
            set;
        }

        /// <summary>
        /// 是否提交(0/1)
        /// </summary>
        public int ifsubmit
        {
            get;
            set;
        }

        /// <summary>
        /// 区分模拟题1和真题2
        /// </summary>
        public int exams
        {
            get;
            set;
        }

        /// <summary>
        /// 题目列表
        /// </summary>
        public List<ExamRoom> list
        {
            get;
            set;
        }
    }

    public class ExamRoom
    {
        /// <summary>
        /// 编号
        /// </summary>
        public int id
        {
            get;
            set;
        }

        /// <summary>
        /// 题目
        /// </summary>
        public string title
        {
            get;
            set;
        }

        /// <summary>
        /// 题目类型(选择题0/判断题1)
        /// </summary>
        public int flog
        {
            get;
            set;
        }

        /// <summary>
        /// 问题
        /// </summary>
        public string question
        {
            get;
            set;
        }

        /// <summary>
        /// 答案列表
        /// </summary>
        public List<string> answer
        {
            get;
            set;
        }

        /// <summary>
        /// 所选答案
        /// </summary>
        public string chooseanswer
        {
            get;
            set;
        }

        /// <summary>
        /// 正确答案
        /// </summary>
        public string trueanswer
        {
            get;
            set;
        }

        /// <summary>
        /// 答案说明
        /// </summary>
        public string answerdetail
        {
            get;
            set;
        }

        /// <summary>
        /// 答题所用时间(秒)
        /// </summary>
        public int usetime
        {
            get;
            set;
        }

        /// <summary>
        /// 是否收藏(0/1)
        /// </summary>
        public int ifcollect
        {
            get;
            set;
        }

        /// <summary>
        /// 笔记
        /// </summary>
        public string notebook
        {
            get;
            set;
        }

        /// <summary>
        /// 错误反馈
        /// </summary>
        public string errorbook
        {
            get;
            set;
        }
    }
}